package com.ktjy.lot.config.job;

import com.alibaba.fastjson.JSONArray;
import com.ktjy.lot.config.emqx.EmqxApiClient;
import com.ktjy.lot.mapper.TaskLogMapper;
import com.ktjy.lot.pojo.DeviceEmqxClient;
import com.ktjy.lot.pojo.TaskLog;
import com.ktjy.lot.service.DeviceEmqxClientService;
import com.ktjy.lot.service.TaskInfoService;
import jakarta.annotation.Resource;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * 同步在线设备的运行情况-新增数据-任务
 */
public class LotAddDeviceRunDetailsJob extends QuartzJobBean {

    private static final Logger logger = LoggerFactory.getLogger(LotAddDeviceRunDetailsJob.class);

    @Resource
    TaskLogMapper taskJobMapper;

    @Resource
    EmqxApiClient emqxApiClient;

    @Resource
    DeviceEmqxClientService deviceEmqxClientService;

    @Resource
    TaskInfoService taskInfoService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        String jobName = context.getJobDetail().getKey().getName();
        //1启用 0停用
        if (taskInfoService.isTaskEnabled(jobName) == 1) {
            TaskLog taskLog = new TaskLog();
            taskLog.setJobName(jobName);
            taskLog.setStartTime(new Date());
            Integer count = 0;
            //通过emqx工具类获取目前的设备的信息
            JSONArray onlinCelients = null;
            try {
                onlinCelients = emqxApiClient.getOnlineClients();
                for (int i = 0; i < onlinCelients.size(); i++) {
                    DeviceEmqxClient javaObject = onlinCelients.getJSONObject(i).toJavaObject(DeviceEmqxClient.class);
                    javaObject.setUpdateTime(new Date());
                    deviceEmqxClientService.add(javaObject);
                    count++;
                }
                //1 正常
                taskLog.setStatus(1);
            } catch (Exception e) {
                //0 异常
                taskLog.setStatus(0);
                taskLog.setErrorMessage(e.getMessage());
            } finally {
                taskLog.setBeAffectedCount(count);
                taskLog.setEndTime(new Date());
                taskLog.setUpdateTime(new Date());
                taskJobMapper.insert(taskLog);
            }
        }
    }
}
